package cn.redsoft.turingapi.request;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import cn.redsoft.turingapi.common.util.Consts;
import cn.redsoft.turingapi.exception.TuringRequestException;
import cn.redsoft.turingapi.msg.BaseMsg;
import cn.redsoft.turingapi.msg.CookBookMsg;
import cn.redsoft.turingapi.msg.ErrorMsg;
import cn.redsoft.turingapi.msg.FlightMsg;
import cn.redsoft.turingapi.msg.LinkMsg;
import cn.redsoft.turingapi.msg.NewsMsg;
import cn.redsoft.turingapi.msg.TextMsg;
import cn.redsoft.turingapi.msg.TrainMsg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class TuringRequestHttpClientImpl extends TuringRequest {

	private String url;

	private static Map<Integer, Class<? extends BaseMsg>> map = new HashMap<Integer, Class<? extends BaseMsg>>();
	static {
		map.put(100000, TextMsg.class);
		map.put(305000, TrainMsg.class);
		map.put(306000, FlightMsg.class);
		map.put(200000, LinkMsg.class);
		map.put(302000, NewsMsg.class);
		map.put(308000, CookBookMsg.class);
		map.put(40001, ErrorMsg.class);
		map.put(40002, ErrorMsg.class);
		map.put(40003, ErrorMsg.class);
		map.put(40004, ErrorMsg.class);
		map.put(40005, ErrorMsg.class);
		map.put(40006, ErrorMsg.class);
		map.put(40007, ErrorMsg.class);
	}

	@Deprecated
	public TuringRequestHttpClientImpl() {
		this.url = Consts.TURING_API_REQUEST_ADDRESS + "?key=" + this.getKey()
				+ "&";
	}

	public TuringRequestHttpClientImpl(TuringRequestMetaData metaData) {
		super(metaData);
		this.url = Consts.TURING_API_REQUEST_ADDRESS + "?key=" + this.getKey()
				+ "&";
	}

	protected String doRequest() throws Exception {

		String urlString = this.url
				+ "info="
				+ URLEncoder.encode(this.metaData.getInfo(),
						Consts.TURING_API_CHARACTER_ENCODING);
		if (this.metaData.getUserid() != null) {
			urlString = urlString + "&userid=" + this.metaData.getUserid();
		}

		log.debug("请求图灵官网服务器 : {}", Consts.TURING_API_REQUEST_ADDRESS);
		log.debug("\t==>url : {}", urlString);
		log.debug("\t==>key : {}", this.getKey());
		log.debug("\t==>【info】: 【{}】", this.getInfo());
		log.debug("\t==>userid : {}", this.getUserid());
		log.debug("\t==>loc : {}", this.getLoc());
		log.debug("\t==>lon : {}", this.getLon());
		log.debug("\t==>lat : {}", this.getLat());
		HttpGet request = new HttpGet(urlString);
		HttpResponse response = HttpClients.createDefault().execute(request);
		String result = "";
		if (response.getStatusLine().getStatusCode() == 200) {
			result = EntityUtils.toString(response.getEntity());
			return result;
		}
		this.metaData.setUserid(null);
		return null;
	}

	@Override
	public BaseMsg getResult() throws TuringRequestException {
		String jsonString = null;
		try {
			jsonString = this.doRequest();
		} catch (Exception e) {
			throw new TuringRequestException(e);
		}
		Integer code = this.getMsgCode(jsonString);
		this.log.debug("\t<== 【code】 :【{}】", code);

		Class<? extends BaseMsg> msgClass = map.get(code);

		BaseMsg msg = JSON.parseObject(jsonString, msgClass);
		log.debug("\t<== 【msgType】 :【{}】", msg.getMsgType().getValue());
		log.debug("\t<== msgBean : {}.", msg.toString());
		log.debug("请求成功 .");
		this.setUserid(null);
		return msg;
	}

	protected Integer getMsgCode(String jsonString) {
		try {
			if (jsonString == null) {
				throw new TuringRequestException();
			}
		} catch (Exception e) {
			throw new TuringRequestException(e);
		}

		JSONObject jsonObject = JSON.parseObject(jsonString);
		Integer code = jsonObject.getInteger("code");
		if (code == 0) {
			throw new TuringRequestException("返回数据异常:" + jsonString);
		}
		return code;
	}
}
